﻿
using System;
using System.Collections.Generic;
using TeamTasker.Contracts;
using TeamTasker.Utils;

namespace TeamTasker.Server.BusinessLogic.Staff
{
    public class PlainFileStaffRepositoryConnector : IStaffRepositoryConnector
    {
        public string FilePath { get; set; }

        public bool CheckUser(string login, string password)
        {
            Validate.NotBlank(login, "User login is blank");
            Validate.NotBlank(password, "User password is blank");
            IList<User> users = GetAllUsers();
            foreach (User user in users)
            {
                if (login == user.Login)
                {
                    return true;
                }
            }
            return false;
        }

        public IList<User> GetAllUsers()
        {
            Validate.NotBlank(FilePath, "Staff repository file path is not specified");
            string[] lines = FileUtils.ReadFileAsStrings(FilePath);
            IList<User> users = new List<User>();
            foreach (string line in lines)
            {
                // Line format: userLogin, userFullName, userEmail
                string[] tokens = line.Split(',');
                if (tokens.Length != 3)
                {
                    throw new ApplicationException(
                        "Text line doesn't conform user entry format [userLogin, userFullName, userEmail]: " + line);
                }
                var user = new User
                {
                    Login = tokens[0].Trim(),
                    FullName = tokens[1].Trim(),
                    Email = tokens[2].Trim()
                };
                users.Add(user);
            }
            return users;
        }

        public IList<User> GetModifiedUser(DateTime since)
        {
            throw new System.NotImplementedException();
        }
    }
}
